# -*- coding: utf-8 -*-

from . import guessImg_baidu
from . import guessImg_sogou
# import guessImg_baidu
# import guessImg_sogou
import threading
from datetime import datetime
import time

import inspect
import ctypes


class GsCtrl(object):
    def __init__(self):
        self.result = {"guessWord": "", "details": ""}

    def _postImgTask(self, t, n, p):
        tmp = {}
        if t == "baidu":
            tmp = guessImg_baidu.BaiduGuessImg(n, p).tryGuess()
            # self.result["from"] = "baidu"
        elif t == "sogou":
            pass
            tmp = guessImg_sogou.SogouGuessImg(n, p).tryGuess()
            # self.result["from"] = "sogou"
        print("postImgTask ----------%s , %s" % (t, datetime.now()))
        if tmp and tmp["guessWord"]:
            self.result = tmp

    def getGuessWord(self, imgname, imgpath, otime):
        print("start post img task %s -------------" % datetime.now())

        t1 = threading.Thread(target=self._postImgTask,
                              args=("baidu", imgname, imgpath))
        t2 = threading.Thread(target=self._postImgTask,
                              args=("sogou", imgname, imgpath))
        t1.start()
        t2.start()

        while (not self.result["guessWord"]) and otime > 0:
            print("every 1 second for wait result")
            otime = otime - 1
            time.sleep(1)

        # 通过except来将线程关闭
        try:
            self._async_raise(t1.ident, SystemExit)
            self._async_raise(t2.ident, SystemExit)
        except Exception as e:
            print("stop thread err = ", e)

        print("stop thread ........", datetime.now())

        if "from" not in self.result :
            self.result["from"] = ""

        return self.result

    def _async_raise(self, tid, exctype):
        """raises the exception, performs cleanup if needed"""
        tid = ctypes.c_long(tid)
        if not inspect.isclass(exctype):
            exctype = type(exctype)
        res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
            tid, ctypes.py_object(exctype))
        if res == 0:
            raise ValueError("invalid thread id")
        elif res != 1:
            # """if it returns a number greater than one, you"re in trouble,
            # and you should call it again with exc=NULL to revert the effect"""
            ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
            raise SystemError("PyThreadState_SetAsyncExc failed")

    # getGuessWord("hj.png","./media/img/hj.png",15)
    # getGuessWord("pj.png","./media/img/pj.png",15)
    # getGuessWord("tt.png","./media/img/tt.png",15)
